package com.example.demodatadruid.controller;

import com.example.demodatadruid.Entity.Employee;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/employees")
public class EmployeeController {

    @Autowired(required = false)
    JdbcTemplate jdbcTemplate;

    @GetMapping("/")
    public List<Employee> getAllEmployees(){
        String sql = "select * from employee";

        List<Employee> emps =  jdbcTemplate.query(sql,new BeanPropertyRowMapper<>(Employee.class));
        return emps;
    }

    @GetMapping("/{id}")
    public Employee GetEmployeeByID(@PathVariable Integer id){
        String sql = "select * from employee where id=?";
        RowMapper<Employee> rowMapper=new BeanPropertyRowMapper<>(Employee.class);
        Employee employee = jdbcTemplate.queryForObject(sql, rowMapper, id);
        return employee;


    }
    
    @PostMapping("/")
    public Integer addEmployee(@RequestBody Employee employee){
        System.out.println(employee.getLast_name());

        String sql = "insert into employee(last_name, email, gender, department, birth)" +
                "values(?,?,?,?,?)";

        Integer count = jdbcTemplate.update(sql,
                employee.getLast_name(),
                employee.getEmail(),
                employee.getGender(),
                employee.getDepartment(),
                employee.getBirth()
        );
        return count;
    }
    @PutMapping("/{id}")
    public Integer updateUser(@PathVariable Integer id, @RequestBody Employee employee){

        String sql = "update employee set last_name=?,email=? where id=?";

        Integer count = jdbcTemplate.update(sql,
                employee.getLast_name(),
                employee.getEmail(),
                employee.getId());
        return count;
    }
    @DeleteMapping("/{id}")
    public Integer deleteEmployeesByID(@PathVariable Integer id){

        String sql = "delete from employee where id =?";

        return jdbcTemplate.update(sql, id);
    }
}
